package com.example.demo.service.imply;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.exception.MyUncheckedException;
import com.example.demo.mapper.*;
import com.example.demo.pojo.dto.QuestionDTO;
import com.example.demo.pojo.entity.QuestionBank;
import com.example.demo.pojo.entity.QuestionFile;
import com.example.demo.pojo.entity.QuestionLabel;
import com.example.demo.pojo.entity.SubjectFile;
import com.example.demo.pojo.query.BankQuery;
import com.example.demo.pojo.store.BankStore;
import com.example.demo.pojo.vo.QuestionVO;
import com.example.demo.service.IBankService;
import com.example.demo.utils.ImportQuestion;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author fjh
 */
@Service
@RequiredArgsConstructor
public class IBankServiceImply extends ServiceImpl<QuestionBankMapper, QuestionBank> implements IBankService {
    private final QuestionBankMapper questionBankMapper;
    private final QuestionClassificationMapper questionClassificationMapper;
    private final QuestionLabelMapper questionLabelMapper;
    private final QuestionCategoryMapper questionCategoryMapper;
    private final BankStore bankStore;
    private final QuestionFileMapper questionFileMapper;
    private final SubjectFileMapper subjectFileMapper;
    /**
     * 工具处理
     */
    //判断是否满足筛选要求
    boolean isRightQuestion(BankQuery bankQuery, QuestionVO questionVO){
        //名字的比较
        if(!bankQuery.getQuestionBankName().isEmpty()){
//            System.out.println("进入名字比较");
            if(questionVO.getQuestionName()!=null&&!(questionVO.getQuestionName().contains(bankQuery.getQuestionBankName()))){
                return false;
            }
        }
        //学科比较
        if(bankQuery.getSubjectId()!=null){
//            System.out.println("进入学科比较");
            if(!Objects.equals(questionVO.getRootId(), bankQuery.getSubjectId())){
                return false;
            }
        }
        //题型比较
        int count=0;
        if(!questionVO.getLabelIds().isEmpty()&& !bankQuery.getLabelIds().isEmpty()){
//            System.out.println("进入题型比较");
            for(int i=0;i<questionVO.getLabelIds().size();i++){
                int labelId = questionVO.getLabelIds().get(i);
                if(bankQuery.getLabelIds().contains(labelId)){
                    break;
                }else{
                    count++;
                }
            }
            if(count==questionVO.getLabelIds().size()){
                return false;
            }
        }
        count=0;
        //题种类比较
        if(!bankQuery.getCategoryIds().isEmpty()){
//            System.out.println("进入题种类比较");
            if(!(bankQuery.getCategoryIds().contains(questionVO.getCategory()))){
                return false;
            }
        }
        return true;
    }
    //根据传入的数据构建出用于更新插入的题目

    //完善题目的html信息
    QuestionVO completeQuestionBank(QuestionVO questionVO){
        if(questionVO.getQuestionName()!=null&&questionVO.getHtmlQuestionName()==null){
            questionVO.setHtmlQuestionName(questionVO.getQuestionName());
        }
        if(questionVO.getParse()!=null&&questionVO.getHtmlParse()==null){
            questionVO.setHtmlParse(questionVO.getParse());
        }
        if(questionVO.getOptionList()!=null&&questionVO.getHtmlOptionsList()==null){
            questionVO.setHtmlOptionsList(questionVO.getOptionList());
        }
        if (questionVO.getOptions()!=null&&questionVO.getHtmlOptions()==null){
            questionVO.setHtmlOptions(questionVO.getOptions());
        }
        return questionVO;
    }
    /**
     * service
     */
    //进行筛选然后加入到bean中
    @Override
    public List<QuestionVO> queryQuestion(BankQuery bankQuery) {
        if(bankQuery.getQuestionBankName()==null) {
            bankQuery.setQuestionBankName("");
        }
        System.out.println("过滤器");
        System.out.println(bankQuery);
        //获得所有题目信息再将与题型表和题类表连接
//        List<Integer>questionIdList=questionFileMapper.searchQuestionBankByRootId(bankQuery.getFileId());
        QueryWrapper<QuestionFile>fileQueryWrapper=new QueryWrapper<>();
        fileQueryWrapper.eq("file_id",bankQuery.getFileId());
        List<Integer>questionIdList=questionFileMapper.selectList(fileQueryWrapper).stream()
                // 提取每个 QuestionFile 对象的 id 属性
                .map(QuestionFile::getQuestionId)
                // 收集到新的列表中
                .collect(Collectors.toList());
        List<QuestionVO> needQuestions = new ArrayList<>();
        SubjectFile subjectFile=subjectFileMapper.selectById(bankQuery.getFileId());
        if(!questionIdList.isEmpty()){
            List<QuestionBank> allQuestions = questionBankMapper.selectBatchIds(questionIdList);
            //添加题目
            for (int i = 0; i < allQuestions.size(); i++) {
                QuestionBank questionBank = allQuestions.get(i);
                QuestionVO questionVO = new QuestionVO();
                questionVO.initFile(subjectFile);
                Integer categoryId = questionBank.getCategory();
                Integer bankId = questionBank.getId();
                String options=questionBank.getOptions();
                String htmlOptions=questionBank.getHtmlOption();
                if(categoryId!=null){
                    questionVO.setCategoryName(questionCategoryMapper.searchName(categoryId));
                }
                questionVO.initBank(questionBank);
                if(bankId!=null){
                    List<Integer> labelIdList = questionClassificationMapper.searchLabelIdListByBankId(bankId);
                    //分支---题目(绝对有题目进行关联)
                    if (labelIdList != null && !labelIdList.isEmpty()) {
                        for (Integer integer : labelIdList) {
                            QuestionLabel questionLabel = questionLabelMapper.selectById(integer);
                            questionVO.initLabel(questionLabel);
                            //获取题目的学科分支
                            int index = questionLabel.getNodeId().indexOf('-');
                            Integer rootId = Integer.parseInt(questionLabel.getNodeId().substring(0, index));
                            questionVO.setRootId(rootId);
                        }
                    }
                }
                if(options!=null&&!(options.isEmpty())){
                    questionVO.initOptions(options,htmlOptions);
                }
                //根据筛选条件将正确的数目返回
                boolean flag=isRightQuestion(bankQuery,questionVO);
                if(flag){
                    needQuestions.add(questionVO);
                }
            }
        }
        //添加文件
        //--1根据文件id去查找当前文件下的子目录
        if(bankQuery.getFileFlag()==1){
            List<SubjectFile>subjectFileList=subjectFileMapper.selectChildrenFile(subjectFile.getNodeId(),subjectFile.getLevel()+1);
            for(int i=0;i<subjectFileList.size();i++){
                QuestionVO questionVO=new QuestionVO();
                questionVO.initFile(subjectFileList.get(i));
                questionVO=completeQuestionBank(questionVO);
                needQuestions.add(0,questionVO);
            }
        }
        return needQuestions;
    }
    //只进行分页查询
    @Override
    public List<QuestionVO> queryPage(int page, int size) {
        return bankStore.queryPage(page, size);
    }

    @Override
    public QuestionVO searchByIdFromStore(int id) {
        QuestionBank questionBank=questionBankMapper.selectById(id);
        Integer categoryId = questionBank.getCategory();
        Integer bankId = questionBank.getId();
        String options=questionBank.getOptions();
        String htmlOptions=questionBank.getHtmlOption();
        QuestionVO questionVO=new QuestionVO();
        if(categoryId!=null){
            questionVO.setCategoryName(questionCategoryMapper.searchName(categoryId));
        }
        questionVO.initBank(questionBank);
        if(bankId!=null){
            List<Integer> labelIdList = questionClassificationMapper.searchLabelIdListByBankId(bankId);
            //分支---题目(绝对有题目进行关联)
            if (labelIdList != null && !labelIdList.isEmpty()) {
                for (Integer integer : labelIdList) {
                    QuestionLabel questionLabel = questionLabelMapper.selectById(integer);
                    questionVO.initLabel(questionLabel);
                    //获取题目的学科分支
                    int index = questionLabel.getNodeId().indexOf('-');
                    Integer rootId = Integer.parseInt(questionLabel.getNodeId().substring(0, index));
                    questionVO.setRootId(rootId);
                }
            }
        }
        if(options!=null&&!(options.isEmpty())) {
            questionVO.initOptions(options,htmlOptions);
        }
        //补充题目的文件信息
        LambdaQueryWrapper<QuestionFile> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QuestionFile::getQuestionId, questionBank.getId()); // 使用Lambda表达式指定字段
        List<QuestionFile> questionFileList = questionFileMapper.selectList(lambdaQueryWrapper);
        List<Integer>fileIdList=new ArrayList<>();
        for(QuestionFile questionFile:questionFileList){
            fileIdList.add(questionFile.getFileId());
        }
        questionVO.setFileIdList(fileIdList);
        return completeQuestionBank(questionVO);
    }


}
